package com.gdsz.libbasic.view.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import com.gdsz.libbasic.extensions.getViewBinding



abstract class BasePagingAdapter<T : Any, VB : ViewDataBinding>(
    diffCallback: DiffUtil.ItemCallback<T> = itemCallback()) :
    PagingDataAdapter<T, BindViewHolder<VB>>(diffCallback) {
    protected lateinit var context:Context
    companion object {
        fun <T : Any> itemCallback(
            areItemsTheSame: (T, T) -> Boolean = { old, new -> old == new },
            areContentsTheSame: (T, T) -> Boolean = { old, new -> old == new },
            getChangePayload: (T, T) -> Any? = { _, _ -> null }
        ): DiffUtil.ItemCallback<T> {
            return object : DiffUtil.ItemCallback<T>() {
                override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
                    return areItemsTheSame(oldItem, newItem)
                }

                override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
                    return areContentsTheSame(oldItem, newItem)
                }

                override fun getChangePayload(oldItem: T, newItem: T): Any? {
                    return getChangePayload(oldItem, newItem)
                }
            }
        }
    }

    override fun onBindViewHolder(holder: BindViewHolder<VB>, position: Int) {
        with(holder.binding) {
            getItem(position)?.let {
                onBindViewHolder(it, position)
            }
            executePendingBindings()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindViewHolder<VB> {
        context = parent.context
        return with(getViewBinding<VB>(LayoutInflater.from(parent.context), parent, 1)) {
            setListener()
            BindViewHolder(this)
        }
    }

    open fun VB.setListener() {}
    abstract fun VB.onBindViewHolder(itemData: T, position: Int)


    protected var onItemClickListener: ((type: Int, position: Int, itemData: T) -> Unit)? = null


    fun onItemClickListener(block: (type: Int, position: Int, itemData: T) -> Unit) {
        onItemClickListener = block
    }


    open fun refreshByPotion(position: Int, itemData: T) {}


}